package com.example.dell.fastshopping.Trade;

import android.Manifest;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.dell.fastshopping.R;
import com.example.dell.fastshopping.network.http.BaseResponse;
import com.example.dell.fastshopping.utils.DESUtils;
import com.example.dell.fastshopping.utils.ToastUtils;
import com.google.gson.GsonBuilder;

import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

//提现
public class TradeExtraclActivity extends AppCompatActivity {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.input_name)
    EditText inputName;
    @BindView(R.id.alipay_num)
    EditText alipayNum;
    @BindView(R.id.extral_num)
    EditText extralNum;
    @BindView(R.id.set_most_money)
    TextView set_most_money;
    @BindView(R.id.most_moeny_num)
    TextView mostMoenyNum;
    @BindView(R.id.yzm_text)
    TextView yzmText;
    @BindView(R.id.getcode)
    TextView getcode;
    @BindView(R.id.endTime)
    TextView endTime;
    @BindView(R.id.confirm)
    TextView confirm;
    @BindView(R.id.pws)
    EditText pws;
    @BindView(R.id.code)
    EditText code;
    private double money;
    private TradeMoenyMolder molder;
    private MyHandle myHandle;
    private int originTime = 60;
    private String from;
    private int gradId;
    private String gradName;

    private static class MyHandle extends Handler {

        private final WeakReference<TradeExtraclActivity> weakReference;

        public MyHandle(TradeExtraclActivity tradeExtraclActivity) {
            weakReference = new WeakReference<>(tradeExtraclActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (weakReference.get() != null) {
                weakReference.get().setTime();
            }
        }
    }

    private void setTime() {
        --originTime;
        if (originTime == 0) {
            getcode.setVisibility(View.VISIBLE);
            endTime.setVisibility(View.GONE);
            originTime = 60;
        } else {
            endTime.setText("剩余" + originTime + "s");
            myHandle.sendEmptyMessageDelayed(1, 1000);
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trade_extracl);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        title.setText("提现");
        Intent intent = getIntent();
        money = Double.valueOf(intent.getStringExtra("money"));
        from = intent.getStringExtra("from");
        gradId = intent.getIntExtra("gradId", -1);
        gradName = intent.getStringExtra("gradName");

        mostMoenyNum.setText(money + "");
        myHandle = new MyHandle(this);
        molder = ViewModelProviders.of(this).get(TradeMoenyMolder.class);

    }

    @OnClick({R.id.back, R.id.getcode, R.id.confirm, R.id.set_most_money})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.getcode:
                getCode();
                break;
            case R.id.confirm:
                extralMoney();
                break;
            case R.id.set_most_money:
                extralNum.setText(money + "");
                break;
        }
    }


    private void getCode() {
        molder.getTradeMolderCode().observe(this, new Observer<BaseResponse>() {
            @Override
            public void onChanged(@Nullable BaseResponse baseResponse) {
                if (baseResponse.isSuccess()) {
                    getcode.setVisibility(View.GONE);
                    endTime.setVisibility(View.VISIBLE);
                    myHandle.removeCallbacksAndMessages(null);
                    myHandle.sendEmptyMessageDelayed(1, 1000);
                    originTime = 60;
                    endTime.setText("剩余" + originTime + "s");
                }
            }
        });
    }
    private void extralMoney() {
        final String input_name = inputName.getText().toString().trim();
        if (input_name.isEmpty()) {
            ToastUtils.showShort("请填写姓名");
            return;
        }
        final String alipay_num = alipayNum.getText().toString().trim();

        if (alipay_num.isEmpty()) {
            ToastUtils.showShort("请填写支付宝账号");
            return;
        }

        final String extral_num = extralNum.getText().toString().trim();

        if (extral_num.isEmpty() && Double.valueOf(extral_num) > 0) {
            ToastUtils.showShort("请填写提取金额");
            return;
        }
        if (!extral_num.isEmpty() && Double.valueOf(extral_num) < 0.01) {
            ToastUtils.showShort("提取金额不能小于0.01元");
            return;
        }

        String pws_ = pws.getText().toString().trim();
        if (pws_.isEmpty()) {
            ToastUtils.showShort("请填写登录密码");
            return;
        }

        String code_ = code.getText().toString().trim();
        if (code_.isEmpty()) {
            ToastUtils.showShort("请填写验证码");
            return;
        }
        //：amount 提现额度
        // zfbAccount 到账方支付宝账号
        // yzm 验证码
        // pwd 登陆密码
        // payName 真实姓名
        String encode = DESUtils.utilEncode(pws_);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("amount", Double.valueOf(extral_num));
        hashMap.put("zfbAccount", alipay_num);
        hashMap.put("yzm", code_);
        hashMap.put("pwd", encode);
        hashMap.put("payName", input_name);
        if ("ensureMoney".equals(from)) {
            hashMap.put("gradeId", gradId);
            hashMap.put("gradeName", gradName);
        }
        String s = new GsonBuilder().create().toJson(hashMap);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=UTF-8"), s);
        molder.extealmoney(body).observe(this, new Observer<BaseResponse>() {
            @Override
            public void onChanged(@Nullable BaseResponse baseResponse) {
                if (baseResponse.isSuccess()) {
                    toExtralSuccessPage(alipay_num, extral_num);
                }
            }
        });
    }

    private void toExtralSuccessPage(String alipay_num, String extral_num) {
        Intent intent = new Intent(this, ExtralSuccessActivity.class);
        intent.putExtra("alipay_num", alipay_num);
        intent.putExtra("extral_num", extral_num);
        startActivity(intent);
        finish();
    }
}
